﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Project;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using Modules.Project;
using Modules.System.Dept;
using Modules.System.User;
using PmSoft.Utilities;

namespace ManagementApi.Controllers.AdminPannel
{
    /// <summary>
    /// 项目管理员-完工销户申请
    /// </summary>
    [Route("/api/v1/sysUser/completed")]
    [ApiController]
    [Authorize(Roles = "SysUser")]
    public class ProjectCompletedController : ControllerBase
    {
        private readonly ProjectCompletedService projectCompletedService;
        private readonly ManagementApplicationContext applicationContext;
        private readonly ProjectService projectService;
        private readonly UserService userService;
        private readonly DeptService deptService;
        private readonly IMapper mapper;
        private readonly ProjectOwnAuthorizer ownAuthorizer;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectCompletedService"></param>
        /// <param name="applicationContext"></param>
        /// <param name="mapper"></param>
        /// <param name="projectService"></param>
        public ProjectCompletedController(ProjectCompletedService projectCompletedService, UserService userService, DeptService deptService, ManagementApplicationContext applicationContext, IMapper mapper,
        ProjectService projectService, ProjectOwnAuthorizer ownAuthorizer
            )
        {
            this.projectCompletedService = projectCompletedService;
            this.applicationContext = applicationContext;
            this.projectService = projectService;
            this.mapper = mapper;
            this.userService = userService;
            this.deptService = deptService;
            this.ownAuthorizer = ownAuthorizer;
        }

        #region 完工销户申请

        /// <summary>
        /// 新增完工销户申请
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost("create")]
        public ApiResult CreateProjectCompleted(ProjectCompletedEditForm form)
        {
            ProjectCompleted entity = new();
            mapper.Map(form, entity);
            projectCompletedService.Create(entity, form.dicAttachments);
            return ApiResult.Success("创建成功");
        }

        /// <summary>
        /// 编辑完工销户申请
        /// </summary>
        /// <param name="id"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("update/{id}")]
        public ApiResult UpdateProjectCompleted(int id, ProjectCompletedEditForm form)
        {
            var entity = projectCompletedService.GetProjectCompleted(id);
            if (entity == null) return ApiResult.Failure("未查询到完工销户申请信息");

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(entity.ProjectId);

            #endregion 验证数据权限

            mapper.Map(form, entity);
            projectCompletedService.Update(entity, form.dicAttachments);
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// 审核完工销户申请
        /// </summary>
        /// <param name="id"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("audit")]
        public ApiResult AuditProjectCompleted(ProjectCompletedAuditForm form)
        {
            var entity = projectCompletedService.GetProjectCompleted(form.Id);
            if (entity == null) return ApiResult.Failure("未查询到完工销户申请信息");
            if (entity.RefundableAmount < form.RefundAmount) return ApiResult.Failure("实际退还金额不能大于可退还金额");

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(entity.ProjectId);

            #endregion 验证数据权限

            var user = userService.GetUser(applicationContext.CurrentUser?.Id ?? 0);
            var dept = deptService.GetSysDept(user?.DeptId ?? 0);
            entity.RefundAmount = form.RefundAmount;
            entity.AuditType = form.AuditType;
            entity.RefundReason = form.RefundReason ?? string.Empty;
            if (form.AuditType == ProjectConstants.完工销户申请状态.审核通过)
            {
                projectCompletedService.Audit(entity, dept?.Name ?? string.Empty, dept?.Code ?? string.Empty);
            }
            else
            {
                projectCompletedService.AuditFail(entity);
            }
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// 删除完工销户申请
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        public ApiResult DeleteProjectCompleted(string ids)
        {
            var datas = projectCompletedService.GetProjectCompleteds(ValueUtility.ConvertToList<int>(ids));

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(datas.Select(i => i.ProjectId));

            #endregion 验证数据权限

            projectCompletedService.Deleted(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// 完工销户申请表单数据
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ApiResult<ProjectCompletedDto> GetProjectCompleted(int id)
        {
            ProjectCompletedDto projectCompletedDto = new ProjectCompletedDto();
            ProjectCompleted? data = projectCompletedService.GetProjectCompleted(id);
            if (data == null)
                return ApiResult<ProjectCompletedDto>.Failure("完工销户申请不存在");

            return ApiResult<ProjectCompletedDto>.Success(data.AsDto(applicationContext));
        }

        /// <summary>
        /// 获取完工销户申请列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<ProjectCompletedDto>> QueryProjectCompleteds([FromQuery] ProjectCompletedQuery query, int pageNum = 1, int pageSize = 20)
        {
            var data = projectCompletedService.GetProjectCompleteds(query, pageNum, pageSize);
            var dtos = data.AsPageDto(source => { return source.AsDto(applicationContext); });
            return ApiResult<PageDto<ProjectCompletedDto>>.Success(dtos);
        }

        #endregion 完工销户申请
    }
}